package com.blb.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 等待和通知机制
 */
public class WaitNotifyDemo2 {

    //创建同步锁对象
    private Lock lock = new ReentrantLock();
    //获得Condition对象
    private Condition condition = lock.newCondition();

    public void testWait(){
        System.out.println(Thread.currentThread().getName()+"执行了！！");
        lock.lock();
        try {
            //当前线程等待
            condition.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName()+"结束了！！");
    }

    public void testNotify(){
        lock.lock();
        try {
            //通知所有等待的子线程
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyDemo2 demo = new WaitNotifyDemo2();
        //启动一个线程执行等待功能
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                demo.testWait();
            }).start();
        }
        //3s主线程通知
        Thread.sleep(3000);
        demo.testNotify();
    }
}
